package com.elcl.network;

import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.elcl.widget.comp.toast.ToastUtils;
import com.elcl.storage.ApplicationCache;
import com.elcl.util.BaseDialogUtils;
import com.squareup.okhttp.Call;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.FormEncodingBuilder;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * Created by lichunlin on 16/8/8.
 */
public class OkHttp {

    public static final int IS_NET_FAILED = 0x404;//网络加载失败
    public static final int RECOGNISE_FAILED = 0x1001;//认证失败

    private static FormEncodingBuilder builder = null;

    private static final OkHttpClient mOkHttpClient = new OkHttpClient();

    private static OkHttp okHttp;

    public static OkHttp getInstance() {
        if (null == okHttp) {
            okHttp = new OkHttp();
        }
        return okHttp;
    }

    static {
        mOkHttpClient.setConnectTimeout(10, TimeUnit.SECONDS);
        mOkHttpClient.setWriteTimeout(10, TimeUnit.SECONDS);
        mOkHttpClient.setReadTimeout(10, TimeUnit.SECONDS);
    }

    public FormEncodingBuilder getFBuilder() {
        if (null == builder) {
            builder = new FormEncodingBuilder();
        }
        return builder;
    }

    //get请求
    public void get(String url, final Handler handler, final int reqId) {
        if (NetWorkUtils.isNetworkAvailable(ApplicationCache.context)) {
            getByServer(url, handler, reqId);
        } else {
            ToastUtils.showToast("没有网络连接");
        }
    }

    private void getByServer(String url, final Handler handler, final int reqId) {
        //创建okHttpClient对象
        final Request request = new Request.Builder()
                .url(url)
                .build();
        Call call = mOkHttpClient.newCall(request);
        //请求加入调度
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {
                ToastUtils.showToast("网络加载失败");
                BaseDialogUtils.dismissProgressDialog();
                handler.sendEmptyMessage(IS_NET_FAILED);
            }

            @Override
            public void onResponse(final Response response) throws IOException {
                BaseDialogUtils.dismissProgressDialog();
                responseSuccess(response, handler, reqId);
            }
        });

    }


    /*********************
     * post请求
     ********************/
    //post请求
    public void post(String url, FormEncodingBuilder builder, final Handler handler, final int reqId, String... isShow) {
        if (NetWorkUtils.isNetworkAvailable(ApplicationCache.context)) {
            Log.i("api", url + "data" + builder);
            if (null != isShow && isShow.length > 0) {
                BaseDialogUtils.showProgressDialog("", isShow[0]);
            }
            builder.add("sessionId", AppContext.getToken());
            Log.i("sessionId", AppContext.getToken());
            postServer(url, builder, handler, reqId);
        } else {
            ToastUtils.showToast("没有网络连接");
        }
    }

    private void postServer(String url, FormEncodingBuilder builder, final Handler handler, final int reqId) {
        Request request = new Request.Builder()
                .url(url)
                .post(builder.build())
                .build();
        mOkHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {
                BaseDialogUtils.dismissProgressDialog();
                ToastUtils.showToast("网络加载失败");
                handler.sendEmptyMessage(IS_NET_FAILED);
            }

            @Override
            public void onResponse(Response response) throws IOException {
                BaseDialogUtils.dismissProgressDialog();
                responseSuccess(response, handler, reqId);
            }
        });
    }


    public static final int NETCODE_FALSE = 0x111;//当返回的结果为空（success为false的时候）

    private void responseSuccess(Response response, final Handler handler, final int reqId) {
        if (response.isSuccessful()) {
            try {
                String htmlStr = null;
                htmlStr = response.body().string();
                JSONObject jsonObject = new JSONObject(htmlStr);
                Log.i("api_result", htmlStr);
                Boolean success = jsonObject.getBoolean("success");
                Message msg = handler.obtainMessage();
                if (success) {
                    msg.obj = htmlStr;
                    msg.what = reqId;
                    handler.sendMessage(msg);
                }else{
                    ToastUtils.showToast(jsonObject.getString("msg"));
                    msg.what = NETCODE_FALSE;
                    handler.sendMessage(msg);
                }
            } catch (JSONException e) {
                e.printStackTrace();
                return;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    public static final String TXT_HTML = "application/json";


    public void postJson(String url, RequestBody requestBody, final Handler handler, final int reqId, String... isShow) {
        if (NetWorkUtils.isNetworkAvailable(ApplicationCache.context)) {
            if (null != isShow && isShow.length > 0) {
                BaseDialogUtils.showProgressDialog("", isShow[0]);
            }
            postJsonServer(url, requestBody, handler, reqId);
        } else {
            ToastUtils.showToast("没有网络连接");
        }
    }

    private void postJsonServer(String url, RequestBody requestBody, final Handler handler, final int reqId) {
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
        mOkHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {
                BaseDialogUtils.dismissProgressDialog();
                ToastUtils.showToast("网络加载失败");
                handler.sendEmptyMessage(IS_NET_FAILED);
            }

            @Override
            public void onResponse(Response response) throws IOException {
                BaseDialogUtils.dismissProgressDialog();
                responseSuccess(response, handler, reqId);
            }
        });
    }


}
